package org.gavin.core.advice;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.util.*;


/**
 * 请求头增强
 * ————————————————
 * 版权声明：本文为CSDN博主「o_瓜田李下_o」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
 * 原文链接：https://blog.csdn.net/weixin_43931625/article/details/104998427
 * @author admin
 */
public class HttpServletRequestAdvice extends HttpServletRequestWrapper {

    public HttpServletRequestAdvice(HttpServletRequest request) {
        super(request);
    }

    private Map<String, String> headers = new HashMap<>();

    public void addHeader(String name, String value) {
        headers.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (headers.containsKey(name)) {
            value = headers.get(name);
        }
        return value;
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        names.addAll(headers.keySet());
        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> list = Collections.list(super.getHeaders(name));
        if (headers.containsKey(name)) {
            list.clear();
            list.add(headers.get(name));
        }
        return Collections.enumeration(list);
    }

}
